<template>
  <div class="order">
    <div class="top">
      <div class="top_left">
        <selectTool
          :colmuns="headerConfig"
          :model-form="configData"
          @onFormChange="getOrderList"
        ></selectTool>
      </div>
      <div class="right">
        <el-button
          type="primary"
          @click="openDialog"
          v-permission="'order:saveOrUpdate'"
          >添加订单</el-button
        >
      </div>
    </div>
    <div class="content">
      <newTable
        :table-config="tableConfig"
        :table-data="tableList"
        :option-list="tableOptionList"
        :options="true"
        @clickBtn="go"
      ></newTable>
    </div>
    <div class="footer">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        @prev-click="prev"
        @change="sizeChange"
        @next-click="next"
      />
    </div>
  </div>

  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="650">
    <div style="padding: 10px">
      <el-form
        label-width="80px"
        :model="addData"
        :rules="addDataRules"
        ref="addDataRef"
      >
        <el-form-item label="仓库名称" prop="origin_id">
          <el-select
            :disabled="addType === 'info' ? true : false"
            v-model="addData.origin_id"
            placeholder="请选择仓库名称"
            @change="getWarehouseInfo($event)"
            ><el-option
              v-for="item in warehouseOptions"
              :label="item.label"
              :value="item.value"
          /></el-select>
        </el-form-item>
        <el-form-item label="店铺名称" prop="destination_id">
          <el-select
            :disabled="addType === 'info' ? true : false"
            v-model="addData.destination_id"
            placeholder="请选择店铺名称"
            @change="getStoreInfo($event)"
            ><el-option
              v-for="item in storeOptions"
              :label="item.label"
              :value="item.value"
          /></el-select>
        </el-form-item>
      </el-form>
      <div>
        <div class="store-top" v-show="addType !== 'info'">
          <span>已选择的商品</span>
          <span>仓库可用容量：{{ usedSpace + "/" + totalSpace }}</span>
        </div>
        <el-table :data="storeDataList" height="250" style="width: 100%">
          <el-table-column prop="goods_name" label="商品名称" />
          <el-table-column prop="goods_quality" label="商品质量" />
          <el-table-column prop="goods_num" label="数量">
            <template #default="scope">
              <el-input
                :disabled="addType === 'info' ? true : false"
                v-model="scope.row.goods_num"
                type="number"
                :min="1"
                @input="
                  (val) => {
                    if (val > scope.row.quantity) {
                      ElMessage.warning('当前仓库库存不足');
                      scope.row.goods_num = scope.row.quantity;
                    } else {
                      const newUsedSpace = storeDataList.reduce(
                        (sum, item, index) =>
                          sum +
                          (index === scope.$index
                            ? val * item.goods_quality
                            : item.goods_num * item.goods_quality),
                        0
                      );
                      if (addType !== 'info' && newUsedSpace > totalSpace) {
                        ElMessage.warning('仓库可用容量不足');
                        scope.row.goods_num = Math.floor(
                          (totalSpace -
                            usedSpace +
                            scope.row.goods_num * scope.row.goods_quality) /
                            scope.row.goods_quality
                        );
                      }
                    }
                  }
                "
              />
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="最大数量" />
          <el-table-column
            label="操作"
            width="80"
            align="center"
            v-if="addType !== 'info'"
          >
            <template #default="scope">
              <el-button
                type="text"
                style="color: red"
                @click="storeDataList.splice(scope.$index, 1)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-button
        v-if="addType !== 'info'"
        type="primary"
        style="margin-left: 16px; margin-top: 10px"
        @click="openStoreDialog"
      >
        选择商品
      </el-button>
    </div>
    <template #footer>
      <div class="dialog-footer" v-if="addType !== 'info'">
        <el-button type="primary" @click="add(addDataRef, permissionValue)">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  <el-drawer v-model="storeList" :direction="direction" size="40%">
    <template #header>
      <h4>仓库已有商品</h4>
    </template>
    <template #default>
      <div>
        <el-table
          ref="multipleTableRef"
          :data="allGoodsData"
          row-key="goods_id"
          style="width: 100%"
          height="550"
          @selection-change="handleSelectionChange"
          show-overflow-tooltip
        >
          <el-table-column
            type="selection"
            :selectable="selectable"
            width="55"
          />
          <el-table-column prop="goods_name" label="商品名称" />
          <el-table-column prop="goods_brand" label="商品品牌" />
          <el-table-column prop="goods_type" label="商品类型" />
          <el-table-column prop="goods_quality" label="商品质量" />
          <el-table-column prop="quantity" label="商品数量" />
          <el-table-column prop="goods_unit" label="商品单位" />
        </el-table>
      </div>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClick">取消</el-button>
        <el-button type="primary" @click="confirmClick">添加</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import {
  getOrderListApi,
  saveOrUpdateOrderApi,
  deleteOrderApi,
  getOrderByIdApi,
  confirmOrderApi,
  confirmStoreApi,
} from "@/api/orderApi";
import { getWarehouseListApi, getWarehouseByIdApi } from "@/api/warehouseApi";
import {
  getStoreListApi,
  getStoreByIdApi,
  getStoreByManagerApi,
} from "@/api/storeApi";
import { getGoodsListApi } from "@/api/goodsApi";
import { onMounted, reactive, ref, watch } from "vue";
import selectTool from "@/components/selectTool/index.vue";
import newTable from "@/components/newTable/index.vue";
import {
  headerConfig,
  configData,
  tableConfig,
  tableList,
  tableOptionList,
  addDataRules,
  addDataRef,
  permissionList,
  permissionValue,
} from "./config";
import { ElMessage, type FormInstance } from "element-plus";
import { convertToTreeData } from "@/utils/routeGenerator";

/**
 * @description 添加部门弹窗
 */
const dialogVisible = ref(false);

const dialogTitle = ref("添加订单");

const addType = ref("");

const storeList = ref(false);
const direction = ref("rtl");
const cancelClick = () => {
  storeList.value = false;
};
const storeDataList = ref([]);
const selectGoodsList = ref([]);
const confirmClick = () => {
  storeList.value = false;
  storeDataList.value = storeDataList.value.concat(selectGoodsList.value);
};
const openStoreDialog = () => {
  if (addData.origin_id === "" || addData.destination_id === "") {
    ElMessage.warning("请先选择仓库/店铺");
    return;
  }
  storeList.value = true;
};
const warehouseOptions = ref([]);
/**
 * @description 获取全部仓库列表
 */
const getWarehouseOptions = () => {
  getWarehouseListApi({ pageSize: -1 }).then((res: any) => {
    console.log("仓库列表", res);
    warehouseOptions.value = res.data.list.map((item: any) => {
      return {
        value: item.id,
        label: item.name,
      };
    });
  });
};

const storeOptions = ref([]);
/**
 * @description 获取全部门面列表
 */
const getStoreOptions = () => {
  getStoreListApi({ pageSize: -1 }).then((res: any) => {
    console.log("门面列表", res);
    storeOptions.value = res.data.list.map((item: any) => {
      return {
        value: item.id,
        label: item.name,
      };
    });
  });
};
const usedSpace = ref(0);
const totalSpace = ref(0);
/**
 * 获取仓库信息
 * @description
 * @param item
 */
const getStoreInfo = (item: any) => {
  getStoreByIdApi(item).then((res: any) => {
    // console.log("仓库信息", res);
    totalSpace.value = res.data.capacity - res.data.used_space;
  });
};

const allGoodsData = ref([]);
const getWarehouseInfo = (item: any) => {
  getWarehouseByIdApi(item).then((res: any) => {
    console.log("全部商品", res);
    allGoodsData.value = res.data.goodsStockList;
  });
};
const selectable = (row: any) => {
  // console.log("选中", row);
  // console.log("storeDataList", storeDataList.value);
  return (
    storeDataList.value.findIndex(
      (item: any) => item.goods_id === row.goods_id
    ) === -1
  );
};
const handleSelectionChange = (val: any) => {
  console.log("选中", val);
  selectGoodsList.value = val.map((item: any) => {
    return {
      goods_id: item.goods_id,
      goods_name: item.goods_name,
      goods_quality: item.goods_quality,
      quantity: item.quantity,
      goods_num: 1,
    };
  });
};
/**
 * @description 打开添加部门弹窗
 */
const openDialog = () => {
  dialogVisible.value = true;
  dialogTitle.value = "添加订单";
  addData.origin_id = "";
  addType.value = "add";
  storeDataList.value = [];
  getAllPermission();
  permissionValue.value = [];
};

/**
 * @description 表格操作
 */
const go = (item: any, option: String) => {
  // console.log(item, option);
  switch (option) {
    case "delete":
      del(item.row.order_id);
      break;
    case "info":
      getOrderById(item.row);
      break;
    case "distribution":
      distributionOrder(item.row);
      break;
    case "finish":
      finishOrder(item.row);
      break;
    default:
      break;
  }
};

/**
 * @description 添加部门数据
 */
const addData = reactive({
  id: "",
  origin_id: "",
  destination_id: "",
});

/**
 * @description 添加订单
 */
const add = async (formEl: FormInstance | undefined, data?: any) => {
  console.log("ceshi", addData);
  if (storeDataList.value.length === 0) {
    ElMessage.warning("请先选择商品");
    return;
  }
  console.log("选择商品", storeDataList.value);

  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      const newAddData = {
        order: {
          ...addData,
          order_type: 2,
          order_status: "CREATED",
          initiator: JSON.parse(localStorage.getItem("userInfo") || "").name,
        },
        orderStores: storeDataList.value.map((item: any) => {
          return {
            store_id: item.goods_id,
            store_num: item.goods_num,
          };
        }),
      };
      saveOrUpdateOrderApi(newAddData).then((res: any) => {
        dialogVisible.value = false;
        getOrderList();
        formEl.resetFields();
        if (addType.value === "edit") {
          ElMessage.success("修改成功");
        } else {
          ElMessage.success("添加成功");
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

/**
 * @description 编辑订单
 */
const getOrderById = (item: any) => {
  console.log("编辑", item);
  dialogTitle.value = "订单详情";
  addType.value = "info";
  dialogVisible.value = true;
  addData.origin_id = item.origin_id;
  getOrderByIdApi(item.order_id).then((res: any) => {
    console.log("订单详情", res);
    storeDataList.value = res.data.goodsList.map((item: any) => {
      return {
        goods_id: item.goods_id,
        goods_name: item.goods_name,
        goods_quality: item.goods_quality,
        goods_num: item.store_num,
      };
    });
  });
};

const distributionOrder = (item: any) => {
  console.log("完成订单", item);
  if (item.order_status === "FINISH") {
    ElMessage.warning("订单已完成请勿操作");
    return;
  }
  // if (item.order_status === "CREATED") {
  //   ElMessage.warning("配送员未确定");
  //   return;
  // }
  if (item.order_status === "INDELIVERY") {
    ElMessage.warning("配送中请勿操作");
    return;
  }
  confirmOrderApi({
    order: {
      order_id: item.order_id,
      courier: JSON.parse(localStorage.getItem("userInfo") || "").name,
    },
  }).then((res: any) => {
    getOrderList();
    ElMessage.success("确认成功");
  });
};

const finishOrder = async (item: any) => {
  console.log("完成订单", item);
  if (item.order_status === "FINISH") {
    ElMessage.warning("订单已完成请勿操作");
    return;
  }
  if (item.order_status === "CREATED") {
    ElMessage.warning("配送员未确定");
    return;
  }
  let orderStoresList: any = [];
  await getOrderByIdApi(item.order_id).then((res: any) => {
    console.log("订单详情", res);
    orderStoresList = res.data.goodsList.map((item: any) => {
      return {
        store_id: item.goods_id,
        store_num: item.store_num,
      };
    });
  });
  let sendData = {
    order: {
      origin_id: item.origin_id,
      order_id: item.order_id,
      destination_id: item.destination_id,
      // courier: JSON.parse(localStorage.getItem("userInfo") || "").name,
    },
    orderStores: orderStoresList,
  };
  console.log("sendData", sendData);
  confirmStoreApi(sendData).then((res: any) => {
    getOrderList();
    ElMessage.success("完成成功");
  });
};

/**
 * @description 删除订单
 */
const del = (id: number) => {
  // console.log("删除", id);

  deleteOrderApi(id).then((res: any) => {
    // console.log(res);
    getOrderList();
    ElMessage.success("删除成功");
  });
};

/**
 * 订单总条数
 */
const total = ref(0);

const pageNum = ref(1);

const pageSize = ref(10);

/**
 * @description 获取订单列表
 */
const getOrderList = () => {
  getOrderListApi({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    order_id: configData.value.orderId,
    courier: configData.value.courier,
    initiator: configData.value.initiator,
    order_status: configData.value.orderStatus,
    order_type: 2,
  }).then((res: any) => {
    console.log(res);
    tableList.value = res.data.list;
    total.value = res.data.total;
  });
};

/**
 * @description 上一页
 */
const prev = () => {
  console.log("上一页");
  getOrderListApi({
    pageNum: pageNum.value - 1,
    pageSize: 10,
  }).then((res: any) => {
    // console.log(res);
    tableList.value = res.data.list;
    total.value = res.data.total;
  });
};

/**
 * @description 下一页
 */
const next = () => {
  console.log("下一页");
  getOrderListApi({
    pageNum: pageNum.value + 1,
    pageSize: 10,
  }).then((res: any) => {
    // console.log(res);
    tableList.value = res.data.list;
    total.value = res.data.total;
  });
};

/**
 * @description 每页显示条数
 */
const sizeChange = (val: number) => {
  console.log(val);
  pageNum.value = val;
  getOrderListApi({
    pageNum: pageNum.value,
    pageSize: 10,
  }).then((res: any) => {
    // console.log(res);
    tableList.value = res.data.list;
    total.value = res.data.total;
  });
};

const getAllPermission = () => {
  // console.log("获取权限", addType.value);
  permissionList.value = JSON.parse(
    localStorage.getItem("permission") || "[]"
  ).map((item: any) => {
    return {
      key: item.id,
      label: item.name,
      disabled: addType.value === "permission" ? item.id : false,
    };
  });
  // console.log("permissionList", permissionList.value);
};

// 菜单列表
const menuData = ref([]);

// 获取全部菜单权限
const getAllMenu = () => {
  // const arr = convertToTreeData(
  //   JSON.parse(localStorage.getItem("menuList") || "[]")
  // );
  // // console.log("全部菜单", arr);
  // menuData.value = arr;
};

// 获取订单菜单权限
const getMenuByOrderId = (id: number) => {
  // getOrderMenuListApi(id).then((res) => {
  //   // console.log("菜单权限", res);
  //   addData.menuIds = res.data.map((i: any) => i.menu_id + "");
  //   // console.log("ew", addData.menuIds);
  // });
};

// 动态计算 usedSpace
watch(
  () => storeDataList.value,
  (newVal) => {
    usedSpace.value = newVal.reduce(
      (sum, item) => sum + item.goods_num * item.goods_quality,
      0
    );
  },
  { deep: true }
);

onMounted(() => {
  getOrderList();
  getAllPermission();
  getAllMenu();
  getWarehouseOptions();
  getStoreOptions();
});
</script>

<style>
.order {
  display: flex;
  flex-direction: column;
  height: 100%;
  border-radius: 15px;
}

.top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
  padding: 0 20px 0 0;
  background-color: rgb(255, 255, 255);
  border-radius: 15px;
  box-shadow: 1px 1px 5px 1px rgba(0, 0, 0, 0.1); /* 阴影 */
  margin-bottom: 10px;
  flex: 0 0 auto;
}

.content {
  height: 100%;
  display: flex;
  background-color: rgb(255, 255, 255);
  border-radius: 15px;
  box-shadow: 1px 1px 5px 1px rgba(0, 0, 0, 0.1); /* 阴影 */
  flex: 1 1 auto;
  overflow: auto;
  padding: 10px;
}

.footer {
  display: flex;
  justify-content: center;
  margin-top: 10px;
  background-color: rgb(255, 255, 255);
  border-radius: 15px;
  box-shadow: 1px 1px 5px 1px rgba(0, 0, 0, 0.1); /* 阴影 */
  height: 60px;
  flex: 0 0 auto;
}
.store-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
/deep/ .el-drawer__header {
  margin-bottom: 0px !important;
}
</style>
